/**
 * 模型列表测试组件
 * 用于诊断模型显示问题
 */

import React, { useState, useEffect } from 'react';
import { Card, Button, List, Alert, Spin, Typography, Space } from 'antd';
import { ReloadOutlined, ApiOutlined } from '@ant-design/icons';
import { simpleMultiModelService } from '../../services/simple-multi-model.service';

const { Title, Text } = Typography;

export const ModelListTest: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [apiModels, setApiModels] = useState<any[]>([]);
  const [serviceModels, setServiceModels] = useState<string[]>([]);
  const [error, setError] = useState<string | null>(null);

  const testModelLoading = async () => {
    setLoading(true);
    setError(null);
    
    try {
      console.log('🔍 开始测试模型加载...');
      
      // 1. 直接测试API
      console.log('📡 测试 /api/v1/model-configs API...');
      const response = await fetch('http://localhost:8002/api/v1/model-configs');
      if (response.ok) {
        const configs = await response.json();
        console.log('✅ API返回的模型配置:', configs);
        setApiModels(configs);
      } else {
        throw new Error(`API调用失败: ${response.status}`);
      }
      
      // 2. 测试服务
      console.log('🔧 测试 simpleMultiModelService...');
      const models = await simpleMultiModelService.getAvailableModels();
      console.log('✅ 服务返回的模型列表:', models);
      setServiceModels(models);
      
      // 3. 对比结果
      console.log('📊 对比结果:');
      console.log('  - API返回模型数量:', configs.length);
      console.log('  - 服务返回模型数量:', models.length);
      
      if (configs.length !== models.length) {
        console.warn('⚠️ 模型数量不匹配！');
      }
      
    } catch (err) {
      console.error('❌ 测试失败:', err);
      setError(err instanceof Error ? err.message : '未知错误');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    testModelLoading();
  }, []);

  return (
    <div style={{ padding: 16 }}>
      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <ApiOutlined />
            <span>模型列表诊断</span>
          </div>
        }
        extra={
          <Button 
            icon={<ReloadOutlined />} 
            onClick={testModelLoading}
            loading={loading}
          >
            重新测试
          </Button>
        }
      >
        {error && (
          <Alert
            message="测试失败"
            description={error}
            type="error"
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}

        {loading ? (
          <div style={{ textAlign: 'center', padding: 40 }}>
            <Spin size="large" />
            <div style={{ marginTop: 16 }}>
              <Text type="secondary">正在测试模型加载...</Text>
            </div>
          </div>
        ) : (
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            {/* API直接返回的模型 */}
            <div>
              <Title level={5}>
                API直接返回 ({apiModels.length} 个模型)
              </Title>
              <Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
                来源: GET http://localhost:8002/api/v1/model-configs
              </Text>
              <List
                size="small"
                dataSource={apiModels}
                renderItem={(model, index) => (
                  <List.Item>
                    <div style={{ width: '100%' }}>
                      <div><strong>#{index + 1} ID:</strong> {model.id}</div>
                      <div><strong>名称:</strong> {model.name || '未设置'}</div>
                      <div><strong>提供商:</strong> {model.provider || '未知'}</div>
                      <div><strong>状态:</strong> {model.status || '未知'}</div>
                    </div>
                  </List.Item>
                )}
              />
            </div>

            {/* 服务返回的模型 */}
            <div>
              <Title level={5}>
                服务返回 ({serviceModels.length} 个模型)
              </Title>
              <Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
                来源: simpleMultiModelService.getAvailableModels()
              </Text>
              <List
                size="small"
                dataSource={serviceModels}
                renderItem={(modelId, index) => (
                  <List.Item>
                    <div>
                      <strong>#{index + 1}:</strong> {modelId}
                    </div>
                  </List.Item>
                )}
              />
            </div>

            {/* 对比结果 */}
            <div>
              <Title level={5}>诊断结果</Title>
              {apiModels.length === serviceModels.length ? (
                <Alert
                  message="✅ 模型数量匹配"
                  description={`API和服务都返回了 ${apiModels.length} 个模型`}
                  type="success"
                  showIcon
                />
              ) : (
                <Alert
                  message="⚠️ 模型数量不匹配"
                  description={
                    <div>
                      <div>API返回: {apiModels.length} 个模型</div>
                      <div>服务返回: {serviceModels.length} 个模型</div>
                      <div style={{ marginTop: 8, color: '#ff4d4f' }}>
                        可能原因: 模型过滤、初始化失败或数据处理错误
                      </div>
                    </div>
                  }
                  type="warning"
                  showIcon
                />
              )}
            </div>
          </Space>
        )}
      </Card>
    </div>
  );
};

export default ModelListTest;
